<template>
  <div class="company-definite">
    <el-row class="company-title">
      <el-col :span="22">
        <span style="margin-left:17px">{{ companyTitle }}</span>
      </el-col>
      <el-col :span="2" class="right">
        <el-button v-if="!readOnly" type="primary" plain icon="el-icon-plus" :disabled="addDis" size="mini" @click="handleAddTableFromData">新增</el-button>
      </el-col>
    </el-row>
    <el-form ref="tableForm" class="data-form" inline-message :model="formTableData" :rules="tableRules">
      <el-table
        ref="multipleTable"
        v-loading="loading"
        class="definite-list"
        :data="tableFormData"
        :size="detailSize"
        max-height="500px"
        @cell-dblclick="click_edit"
      >
        <el-table-column column-key="2" type="index" label="序号" width="51" align="center" />
        <el-table-column
          prop="orgName"
          :label="companyTitle"
          min-width="80"
          align="center"
          column-key="3"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.action == 'view' || scope.row.action == 'fill'">{{ scope.row.name }}</span>
            <el-form-item v-else prop="name" class="data-form-item">
              <el-input v-model="formTableData.name" placeholder="请选择或输入无" @input="checkOrgName">
                <template slot="append"><el-button icon="el-icon-office-building" @click="handleTenderOrg" /></template>
              </el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          prop="orgCreditCode"
          label="信用代码"
          min-width="80"
          align="center"
          column-key="3"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.action == 'view' || scope.row.action == 'fill'">{{ scope.row.creditCodePic }}</span>
            <el-form-item v-else prop="creditCodePic" class="data-form-item">
              <el-input v-model="formTableData.creditCodePic" readonly clearable placeholder="单位统一社会信用代码" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!readOnly" column-key="10" prop="operation" label="操作" align="center" width="150">
          <template slot-scope="scope">
            <el-button v-if="scope.row.action=== 'add'" size="mini" @click="click_add(scope.row,scope.$index)">保存</el-button>
            <el-button v-if="scope.row.action=== 'add'" size="mini" @click="cancelAdd(scope.row,scope.$index)">取消</el-button>
            <el-button v-if="scope.row.action=== 'edit'" size="mini" @click="click_editSave(scope.row,scope.$index)">保存</el-button>
            <el-button v-if="scope.row.action=== 'edit'" size="mini" @click="cancelEdit(scope.row,scope.$index)">取消</el-button>
            <el-button v-if="scope.row.action=== 'view'" size="mini" @click="click_edit(scope.row,scope.$index)">修改</el-button>
            <el-button v-if="scope.row.action=== 'view'" size="mini" @click="deleteRow(scope.row,scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <!-- 单位选择组件 -->
    <organization ref="selectClient" @organizationList="organizationList" />
  </div>
</template>

<script>
// 单位选择组件
import organization from '@/components/basicinfo/organization/index'
export default {
  name: 'CompanyDefinite',
  components: {
    organization
  },
  props: {
    companyTitle: {
      type: String,
      default: ''
    },
    companyType: {
      type: String,
      default: ''
    },
    companyIndex: {
      type: Number,
      default: 0
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    tableData: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      childrenTitle: '', // 人员选择模板名称
      // 明细表
      isRowAdd: true, // 明細是否可以添加
      addDis: false, // 新增按钮是否可用
      formTableData: {}, // 每一行的表单
      tableFormData: [], // 表格
      loading: false,
      tableRules: {
        name: [
          { required: true, message: '单位名称不得为空', pattern: '[^ \x22]+' }
        ]
      }, // 表格验证
      deleteDetail: [],
      contactOptions: ''
    }
  },
  computed: {
  },
  watch: {
    tableData: {
      deep: true,
      immediate: true,
      handler(val) {
        let newArr = []
        if (val && val.length > 0 && val[0].oldRow === undefined && val[0].action !== 'view') {
          newArr = val.map(item => {
            if (item.creditCodePic === '无') {
              this.addDis = true
            }
            item.action = 'view'
            return item
          })
        } else {
          newArr = val
        }
        if (JSON.stringify(val) !== JSON.stringify(this.tableFormData)) {
          this.tableFormData = newArr
        }
      }
    },
    tableFormData: {
      handler(newVal) {
        this.changetableFormData()
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
  },
  methods: {
    /* 选择单位 start*/
    organizationList(row) {
      this.formTableData = { ...row[0] }
    },
    handleTenderOrg() {
      this.childrenTitle = this.companyTitle
      const organizationType = this.companyType
      this.$refs.selectClient.handleAdd(this.childrenTitle, '0', organizationType, this.formTableData.creditCodePic)
    },
    /* 选择单位 end*/
    /** ****** 动态新增表格start****************/
    // 判断存在表格是否可编辑
    filterTableFromDataEdit(tableFromData) {
      let flg = false
      this.tableFormData.map(item => {
        if (item.action === 'add' || item.action === 'edit') {
          flg = true
        }
      })
      return flg
    },
    // 动态表格新增一行
    handleAddTableFromData() {
      if (this.tableFormData && this.tableFormData.length > 0) {
        if (this.filterTableFromDataEdit(this.tableFormData)) {
          this.msgInfo('请先保存正在编辑的数据')
        } else {
          this.tableFormData.push({
            action: 'add',
            oldRow: {}
          })
          this.addDis = true
          this.handleTenderOrg()
        }
      } else {
        this.tableFormData = []
        this.tableFormData.push({
          action: 'add',
          oldRow: {}
        })
        this.addDis = true
        this.handleTenderOrg()
      }
    },
    // 判断新增按钮是否可用
    checkAddBtn(tableFormData) {
      if (tableFormData.length > 0) {
        this.addDis = false
        tableFormData.map((item) => {
          if (item.action === 'add' || item.action === 'edit' || item.name === '无') {
            this.addDis = true
            return
          }
        })
      } else {
        this.addDis = false
      }
    },
    // 判断明细不能重复
    checkRepeat(tableFormData, row, index) {
      if (tableFormData.length > 0) {
        for (let i = 0; i < tableFormData.length; i++) {
          if (tableFormData[i].name === row.name && i !== index) {
            this.msgInfo('不能填写重复的明细')
            tableFormData[index].action = 'add'
            return false
          }
        }
        tableFormData[index].action = 'view'
        this.checkAddBtn(tableFormData)
      }
    },
    // 监听单位输入
    checkOrgName(val) {
      if (val === '无') {
        this.formTableData.id = ''
        this.formTableData.name = '无'
        this.formTableData.creditCodePic = '无'
      } else {
        this.formTableData.id = ''
        this.formTableData.creditCodePic = ''
      }
    },
    // 检查单位是否为无
    checkOrgNameNull(orgName, orgCreditCode, row, index) {
      if (orgName === '无') {
        this.$confirm('您确定单位名称为’无‘吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableFormData = []
          this.tableFormData = [
            {
              id: '',
              enterpriseType: this.companyType,
              name: '无',
              creditCodePic: '无',
              action: 'view'
            }
          ]
          this.addDis = true
        }).catch(() => {
          this.msgWarning('您已取消')
        })
        return
      }
      if (orgName !== '无' && orgCreditCode === '无') {
        this.msgInfo('请选择已有的单位或者输入“无”')
        return
      }
      if (orgName !== '无' && orgCreditCode === '') {
        this.msgInfo('请选择已有的单位或者输入“无”')
        return
      }
      this.tableFormData[index] = Object.assign(this.tableFormData[index], this.formTableData)
      this.checkRepeat(this.tableFormData, row, index)
      this.emptyFormData()
    },
    // 新增保存操作
    click_add(row, index) {
      this.$refs.tableForm.validate(validate => {
        if (validate) {
          this.checkOrgNameNull(this.formTableData.name, this.formTableData.creditCodePic, row, index)
        }
      })
    },
    // 新增取消
    cancelAdd(row, index) {
      this.emptyFormData()
      this.tableFormData.splice(index, 1)
      this.checkAddBtn(this.tableFormData)
    },
    // 修改保存
    click_editSave(row, index) {
      this.$refs.tableForm.validate(validate => {
        if (validate) {
          this.checkOrgNameNull(this.formTableData.name, this.formTableData.creditCodePic, row, index)
        }
      })
    },
    // 修改取消
    cancelEdit(row, index) {
      this.$set(this.tableFormData, index, row)
      row.action = 'view'
      this.checkAddBtn(this.tableFormData)
      this.emptyFormData()
    },
    // 修改
    click_edit(row, index) {
      if (this.readOnly) return
      if (!this.isReadOnly) {
        if (this.filterTableFromDataEdit(this.tableFormData)) {
          this.msgInfo('请先保存正在编辑的数据')
        } else {
          row.action = 'edit'
          // 将原数据放到oldRow对象中
          row.oldRow = JSON.parse(JSON.stringify({ ...row }))
          this.formTableData = { ... row }
          this.$set(this.tableFormData, index, row)
          this.checkAddBtn(this.tableFormData)
        }
      }
    },
    // 删除
    deleteRow(row, index) {
      this.tableFormData.splice(index, 1)
      if (row.id !== '') {
        this.deleteDetail.push(row.id)
      }
      this.emptyFormData()
      this.checkAddBtn(this.tableFormData)
    },
    // 清空 动态表格
    emptyFormData() {
      this.resetForm('tableForm')
      this.formTableData.id = ''
      this.formTableData.name = ''
      this.formTableData.creditCodePic = ''
    },
    // // 把信息回传给父组件
    changetableFormData() {
      this.$emit('getTableFormData', this.tableFormData, this.companyType)
    }
    /** 动态新增表格end******************/
  }
}
</script>

